package demo6;

import java.util.Stack;

public class PostfixEvaluator {

    // 计算后缀表达式
    public static double evaluatePostfix(String postfix) throws ArithmeticException {
        Stack<Double> stack = new Stack<>();
        String[] tokens = postfix.split(" ");  // 按空格分割

        for (String token : tokens) {
            // 如果是数字，压入栈
            if (isNumeric(token)) {
                stack.push(Double.parseDouble(token));
            }
            
            // 如果是运算符，弹出两个操作数进行计算
            else if (ExpressionEvaluator.isOperator(token.charAt(0))) {
                double val2 = stack.pop();
                double val1 = stack.pop();

                switch (token.charAt(0)) {
                    case '+':
                        stack.push(val1 + val2);
                        break;
                    case '-':
                        stack.push(val1 - val2);
                        break;
                    case '*':
                        stack.push(val1 * val2);
                        break;
                    case '/':
                        // 处理除零情况
                        if (val2 == 0) {
                            throw new ArithmeticException("除数不能为零");
                        }
                        stack.push(val1 / val2);
                        break;
                }
            }
        }
        // 栈顶元素即为表达式的计算结果
        return stack.pop();
    }

    // 检查字符串是否是数字
    private static boolean isNumeric(String token) {
        try {
            Double.parseDouble(token);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }
}